<template>
  <div class="netdisk-container">
    <!-- 侧边栏区域 -->
    <div class="sidebar">
      <div class="sidebar-inner">
        <!-- 左侧菜单 -->
        <div class="sidebar-left">
          <el-menu
              :default-active="activeTag"
              class="el-menu-vertical"
              @select="handleTagSelect"
          >
            <el-submenu index="storage">
              <template #title>
                <i class="fa fa-database"></i>
                <span>我的云盘</span>
              </template>
              <el-menu-item index="allFiles">云盘文件</el-menu-item>
              <el-menu-item index="starred">收藏文件</el-menu-item>
              <el-menu-item index="shared">共享文件</el-menu-item>
              <el-menu-item index="trash">回收站</el-menu-item>
            </el-submenu>
          </el-menu>
        </div>

        <!-- 右侧文件类别按钮 -->
        <div class="sidebar-right">
          <el-button
              class="category-button"
              type="primary"
              :plain="!tags.allTypes"
              @click="handleTypeSelect('allTypes')"
          >全部</el-button>
          <el-button
              class="category-button"
              type="primary"
              :plain="!tags.images"
              @click="handleTypeSelect('images')"
          >图片</el-button>
          <el-button
              class="category-button"
              type="primary"
              :plain="!tags.documents"
              @click="handleTypeSelect('documents')"
          >文档</el-button>
          <el-button
              class="category-button"
              type="primary"
              :plain="!tags.videos"
              @click="handleTypeSelect('videos')"
          >视频</el-button>
          <el-button
              class="category-button"
              type="primary"
              :plain="!tags.audios"
              @click="handleTypeSelect('audios')"
          >音频</el-button>
          <el-button
              class="category-button"
              type="primary"
              :plain="!tags.others"
              @click="handleTypeSelect('others')"
          >其他</el-button>
        </div>
      </div>

    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <div class="toolbar">
        <el-button-group>
          <el-upload
              class="upload-btn"
              action="http://localhost:5080/files/upload"
              :data="{ email:email}"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :on-progress="handleUploadProgress"
              :headers="{'token': $store.getters.token}"
              multiple
              :limit="3"
              :on-exceed="handleExceed"
              :disabled="uploading"
          >
            <el-button type="primary" icon="el-icon-upload">
              {{ uploading ? '上传中...' : '上传文件' }}
            </el-button>
          </el-upload>
          <el-progress
              v-if="uploading"
              :percentage="uploadProgress"
              :stroke-width="6"
              style="width: 200px; margin-left: 10px;"
          ></el-progress>
        </el-button-group>
      </div>

      <div class="file-part">
        <div class="file-grid">
          <div class="filter-info">
            当前筛选:
            <span v-if="activeTag === 'allFiles'">全部文件</span>
            <span v-if="activeTag === 'starred'">收藏文件</span>
            <span v-if="activeTag === 'shared'">共享文件</span>
            <span v-if="activeTag === 'trash'">回收站</span>
            <span v-if="Object.keys(tags).find(key => tags[key] && key !== 'allTypes')">
              - {{ Object.keys(tags).find(key => tags[key] && key !== 'allTypes') }}
            </span>
          </div>

          <!-- 滚动列表容器 -->
          <div class="file-list-container">
            <div class="file-list-header">
              <div class="header-info">文件名</div>
              <div class="header-actions">操作</div>
            </div>

            <!-- 文件列表 -->
            <div class="file-list">
              <FileItem
                  v-for="file in filteredFiles"
                  :key="file.id || file.name"
                  :file="file"
                  @download="downloadFile"
                  @delete="handleFileDelete"
                  @share="shareFile"
                  @toggle-star="handleStarToggle"
              />

              <!-- 空状态提示 -->
              <div class="empty-state" v-if="filteredFiles.length === 0">
                <i class="fa fa-folder-open-o"></i>
                <p>没有符合条件的文件</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import FileItem from '@/components/FileItem.vue'
import { mapGetters } from 'vuex'
import service from '@/utils/request'
export default {
  name: 'Home',
  components: {FileItem},
  data() {
    return {
      uploadDialogVisible: false,
      createFolderDialogVisible: false,
      folderForm: {name: ''},
      loading: {
        upload: false,
        createFolder: false,
        delete: false,
        refresh: false
      },
      activeTag: 'allFiles',
      tags: {
        allTypes: true,
        images: false,
        documents: false,
        videos: false,
        audios: false,
        others: false
      },
      uploading: false,
      uploadProgress: 0,
      uploadFiles: []
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'username',
      'avatar',
      'email',
      'token',
      'fileList',
      'storage',
      'activeFiles',
      'starredFiles',
      'sharedFiles',
      'trashFiles'
    ]),

    // 存储相关计算属性
    storageInfo() {
      return this.$store.getters.storage || { usedStorage: 0, totalStorage: 0 };
    },
    usedStorage() {
      return this.storageInfo.usedStorage || 0;
    },
    totalStorage() {
      return this.storageInfo.totalStorage || 0;
    },
    storagePercentage() {
      const { usedStorage, totalStorage } = this.storageInfo;
      return totalStorage > 0
          ? Math.round((usedStorage / totalStorage) * 100)
          : 0;
    },

    // 文件列表处理
    currentFiles() {
      return (this.fileList || []).map(file => {
        // 调用映射方法，获取主类和子类标识
        const [mainType, subType] = this.getTypeCategory(file.fileType)
        return {
          id: file.fileId,
          name: file.fileName,
          type: file.fileType, // 保留原始完整后缀（如 docx）
          mainType: mainType,  // 主类（如 document/image）
          subType: subType,    // 子类标识（如 doc/pdf）
          size: file.fileSize,
          modified: file.lastModified,
          isStarred: file.isStarred,
          isShared: file.isShared || false,
          isDeleted: file.isDeleted || false
        }
      })
    },

    // 筛选文件
    filteredFiles() {
      let result = [...this.currentFiles]

      // 标签筛选
      if (this.activeTag === 'allFiles') {
        // 我的云盘：只显示未删除的正常文件
        result = result.filter(file => !file.isDeleted);
      } else if (this.activeTag === 'starred') {
        result = result.filter(file => file.isStarred && !file.isDeleted); // 收藏文件也应排除已删除的
      } else if (this.activeTag === 'shared') {
        result = result.filter(file => file.isShared && !file.isDeleted); // 共享文件也应排除已删除的
      } else if (this.activeTag === 'trash') {
        result = result.filter(file => file.isDeleted); // 回收站：只显示已删除的
      }

      // 类型筛选
      if (this.tags.images) {
        result = result.filter(file => file.mainType === 'image')
      } else if (this.tags.documents) {
        result = result.filter(file => file.mainType === 'document')
      } else if (this.tags.videos) {
        result = result.filter(file => file.mainType === 'video')
      } else if (this.tags.audios) {
        result = result.filter(file => file.mainType === 'audio')
      } else if (this.tags.others) {
        result = result.filter(file => file.mainType === 'other')
      }

      return result
    },

    // 上传请求头，添加认证信息
    uploadHeaders() {
      return {
        'Authorization': `Bearer ${this.token}`
      }
    }
  },
  async created() {
    // 页面加载时检查用户是否已登录
    if (!this.token) {
      // 没有token，跳转到登录页
      this.$router.push('/login')
      return
    }

    try {
      const email = this.email || '';
      //后端
       const response = await service.post('/userdata',{email})
      console.log(this.username);
      //前端测试
      //const response = await service.get('/userdata')
      const userData = Array.isArray(response.data) ? response.data[0] : response.data
      if (userData) {
        localStorage.setItem('userData', JSON.stringify(userData))
        this.$store.commit('initUserData', userData)
      }
    } catch (error) {
      console.error('初始化用户数据失败:', error)
      this.$message.error('加载用户数据失败，请重新登录')
      this.$store.commit('logout')
      this.$router.push('/login')
    }
  },
  methods: {
    // 刷新文件列表（从 localStorage 获取最新数据）

    async handleFileDelete({ fileName, permanent }) {
      try {
        // 仅刷新列表，不处理具体删除逻辑
         await this.refreshFileList();
      } catch (error) {
        console.error('刷新列表失败:', error);
      }
    },
    // Home.vue 的 methods 中
    handleStarToggle({ fileName, isStarred, file }) {
      // 1. 找到当前文件在列表中的索引
      const fileIndex = this.currentFiles.findIndex(
          item => item.name === fileName || item.fileName === fileName
      );

      if (fileIndex !== -1) {
        // 2. 直接更新当前文件的 isStarred 状态（触发响应式更新）
        this.$set(this.currentFiles[fileIndex], 'isStarred', isStarred);

        // 3. 同步更新 Vuex 中的文件列表（确保数据源头更新）
        this.$store.dispatch('updateFileStarStatus', {
          fileName: fileName,
          isStarred: isStarred
        });
      }

      // 4. 可选：刷新列表（如果依赖 localStorage 或后端数据）
      this.refreshFileList();
    },

    refreshFileList() {
      // 从localStorage重新加载数据
      const userData = JSON.parse(localStorage.getItem('userData')) || {}
      if (userData.fileList) {
        this.$store.commit('updateUserData', { fileList: userData.fileList })
      }
    },

    // 新增：上传成功回调
    handleUploadSuccess(response, file, fileList) {
      this.uploading = false
      this.uploadProgress = 0

      // 1. 解析后端返回的文件信息（根据实际接口调整）
      const newFile = {
        fileId: response.fileId,
        fileName: file.name,
        fileType: this.getFileType(file.name),
        fileSize: this.formatFileSize(file.size),
        lastModified: new Date().toLocaleString(),
        isStarred: false,
        isShared: false,
        isDeleted: false
      }

      // 2. 更新Vuex中的文件列表
      this.$store.dispatch('addFile', newFile)

      // 3. 提示成功
      this.$message.success(`文件 "${file.name}" 上传成功`)
    },

    // 新增：上传失败回调
    handleUploadError(error, file, fileList) {
      console.error('上传错误详情:', error);
      console.error('响应数据:', error.response?.data); // 后端返回的错误信息
      this.$message.error(`上传失败：${error.response?.data?.msg || error.message}`);
    },

    // 上传进度更新
    handleUploadProgress(event) {
      this.uploadProgress = Math.round(event.percent)
    },

    // 新增：提交上传
    submitUpload() {
      this.uploading = true
      this.$refs.uploadRef.submit()
    },

    handleRemove(file, fileList) {
      console.log(file, fileList)
    },

    handlePreview(file) {
      console.log(file)
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`)
    },

    downloadFile(file) {
      this.$message.success(`文件 "${file.name}" 开始下载`)
      // 实际项目中应调用后端下载接口
      console.log(`下载文件: ${file.name}，ID: ${file.id}`)
    },

    // 标签选择处理
    handleTagSelect(tag) {
      this.activeTag = tag
      this.tags = {allTypes: true, images: false, documents: false, videos: false, audios: false, others: false}
    },

    // 类型选择处理
    handleTypeSelect(type) {
      Object.keys(this.tags).forEach(key => this.tags[key] = false)
      this.tags[type] = true
    },

    refreshFiles() {
      this.$store.dispatch('fetchFiles') // 如果有后端API支持
      this.$message.success('文件列表已刷新')
    },

    handleUpload() {
      this.uploadDialogVisible = true
      // 重置上传组件状态
      this.$nextTick(() => {
        if (this.$refs.uploadRef) {
          this.$refs.uploadRef.clearFiles()
        }
      })
    },

    // 将完整后缀映射到分类
    getTypeCategory(fileType) {
      // 映射关系：key为fileType（完整后缀），value为[主类, 子类标识]
      const typeMap = {
        // 文档类（主类：document）
        'doc': ['document', 'doc'],
        'docx': ['document', 'doc'],
        'pdf': ['document', 'pdf'],
        'xls': ['document', 'excel'],
        'xlsx': ['document', 'excel'],
        'ppt': ['document', 'ppt'],
        'pptx': ['document', 'ppt'],
        'txt': ['document', 'txt'],
        'rtf': ['document', 'txt'],
        'odt': ['document', 'doc'],
        'ods': ['document', 'excel'],
        'odp': ['document', 'ppt'],

        // 图片类（主类：image）
        'jpg': ['image', 'image'],
        'jpeg': ['image', 'image'],
        'png': ['image', 'image'],
        'gif': ['image', 'image'],
        'webp': ['image', 'image'],
        'bmp': ['image', 'image'],
        'tiff': ['image', 'image'],
        'svg': ['image', 'image'],

        // 视频类（主类：video）
        'mp4': ['video', 'video'],
        'avi': ['video', 'video'],
        'mov': ['video', 'video'],
        'wmv': ['video', 'video'],
        'flv': ['video', 'video'],
        'mkv': ['video', 'video'],
        'webm': ['video', 'video'],
        'mpeg': ['video', 'video'],

        // 音频类（主类：audio）
        'mp3': ['audio', 'audio'],
        'wav': ['audio', 'audio'],
        'flac': ['audio', 'audio'],
        'm4a': ['audio', 'audio'],
        'ogg': ['audio', 'audio'],
        'wma': ['audio', 'audio'],
        'aac': ['audio', 'audio'],

        // 其他类
        'zip': ['other', 'zip'],
        'rar': ['other', 'zip'],
        '7z': ['other', 'zip'],
        'tar': ['other', 'zip'],
        'gz': ['other', 'zip'],
        'js': ['other', 'code'],
        'html': ['other', 'code'],
        'css': ['other', 'code'],
        'java': ['other', 'code'],
        'py': ['other', 'code'],
        'vue': ['other', 'code'],
        'json': ['other', 'code'],
        'xml': ['other', 'code'],
        'exe': ['other', 'exe'],
        'dmg': ['other', 'exe'],
        'app': ['other', 'exe'],
        'folder': ['folder', 'folder']
      }

      // 未匹配的类型归为「其他」
      return typeMap[fileType.toLowerCase()] || ['other', 'other']
    },

    // 返回完整后缀
    getFileType(fileName) {
      const ext = fileName.split('.').pop()?.toLowerCase()
      return ext || 'other' // 如 docx/pdf/xlsx，无后缀则为 other
    },

    // 格式化文件大小显示
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    beforeUpload(file) {
      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isLt100M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isLt100M
    },

    handleCreateFolder() {
      this.createFolderDialogVisible = true
      this.folderForm.name = ''
    },

    submitFolderForm() {
      this.$refs.folderFormRef.validate(valid => {
        if (!valid) return

        this.$store.dispatch('createFolder', this.folderForm.name)
        this.createFolderDialogVisible = false
        this.$message.success(`文件夹 "${this.folderForm.name}" 创建成功`)
      })
    },

    async deleteFile({ fileId, permanent }) {
      try {
        if (permanent) {
          // 彻底删除：从文件列表中移除
          const updatedFiles = this.fileList.filter(file => file.fileId !== fileId);
          this.$store.commit('updateUserData', { fileList: updatedFiles });
        } else {
          // 移至回收站：更新文件状态
          const updatedFiles = this.fileList.map(file =>
              file.fileId === fileId ? { ...file, isDeleted: true } : file
          );
          this.$store.commit('updateUserData', { fileList: updatedFiles });
        }

        // 刷新存储使用量（如果需要）
        if (permanent) {
          await this.refreshStorageUsage();
        }
      } catch (error) {
        console.error('更新文件列表失败:', error);
        this.$message.error('操作失败，请刷新页面');
      }
    },
    async refreshStorageUsage() {
      const email = this.email || '';
      //const response = await service.post('/userdata',{email})//后端
      const response = await service.get('/userdata')//前端测试
      const userData = Array.isArray(response.data) ? response.data[0] : response.data
      if (userData) {
        this.$store.commit('initUserData', userData)
      }
    },
    toggleStar(file) {
      this.$store.dispatch('toggleStar', file.id)
      const status = file.isStarred ? '取消收藏' : '收藏'
      this.$message.success(`已${status}文件: ${file.name}`)
    },

    shareFile(file) {
      this.$message.success(`分享链接已复制到剪贴板: https://cloud.example.com/s/${file.id}`)
    },

    handleFileSelect(file) {
      console.log('选中文件:', file)
    },

    logout() {
      this.$store.dispatch('logout')
    }
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.filter-info {
  grid-column: 1 / -1;
  padding: 8px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  color: #666;
  margin-bottom: 16px;
}

.netdisk-container {
  display: flex;
  height: calc(100vh - 60px);
  overflow: hidden;
}

.sidebar {
  width: 260px;
  height: 100%;
  background-color: #ffffff;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
}

.sidebar-inner {
  display: flex;
  flex: 1;
  overflow-y: auto;
}

.sidebar-left {
  width: 160px;
  padding: 8px;
  box-sizing: border-box;
}

.sidebar-right {
  flex: 1;
  padding: 16px 8px;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  display: flex;
}

.category-button {
  margin: 0 !important;
  width: 100%;
}

.progress-container {
  padding: 16px;
  border-top: 1px solid #ebeef5;
}

.progress-text {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
  text-align: center;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.toolbar {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  height: 60px;
  box-sizing: border-box;
}

/* 新增/修改部分 */
.file-part {
  flex: 1;
  overflow: hidden; /* 修改：防止内部滚动影响整体布局 */
  padding: 16px;
}

/* 新增：文件列表容器 */
.file-list-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  height: 100%; /* 占满可用高度 */
  display: flex;
  flex-direction: column;
}

/* 新增：列表头部 */
.file-list-header {
  display: flex;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: 500;
  font-size: 13px;
  color: #666;
}

.header-info {
  flex: 1;
  padding-left: 36px; /* 与文件图标对齐 */
}

.header-actions {
  width: 160px; /* 与操作区宽度匹配 */
  text-align: right;
  padding-right: 16px;
}

/* 修改：文件列表改为垂直排列 */
.file-grid {
  display: block; /* 改为块级布局 */
  flex: 1; /* 占满剩余空间 */
  overflow-y: auto; /* 仅在内容超出时显示滚动条 */
  padding: 8px;
}

/* 新增：空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  color: #909399;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

/* 菜单样式调整 */
.el-menu-vertical .el-menu-item {
  min-width: 100px !important;
  max-width: 100px !important;
  height: 50px !important;
  line-height: 50px !important;
  padding: 0 10px !important;
  text-align: center !important;
}
</style>